<?php
declare (strict_types = 1);

namespace app\validate;

use think\Validate;

class ModuleFieldValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
     protected   $rule = [
         'id|字段ID'  => 'require|number',
         'module_id|模型ID' => 'require|number',
         'form_title|标题' => 'require|max:80',
         'table_field|数据表字段名称' => ['require','max:80','checkTableField'],
         'type|字段类型' => 'require',
         'order|字段排序' => 'require',
         'status|字段状态' => 'require|in:1,2',
         'is_null|字段空值设置' => 'in:1,2',
         'attach_data|数据源' => 'requireAttachData',
         'settings|关联关系' => 'requireSettings'
     ];

    protected $message = [
        'table_field.regex' => '数据表字段请以小写字母和下划线格式添加,下划线不能在开头和结尾'
    ];

    // 自定义验证规则
    public function requireAttachData($value)
    {
        $type = input('param.type');
        if(!in_array($type,['单选','多选','列表','多选列表'])){
            return true;
        }
        if(!empty($value)){
            return true;
        }
        return '数据源不能为空';
    }

    public function requireSettings($value)
    {
        $type = input('param.type');
        if(($type != '关联字段')){
            return true;
        }
        if(empty($value)){
            return '关联关系不能为空';
        }
        if(!is_array($value)){
            return '关联数据类型错误';
        }
        if(empty($value['relation'])){
            return '关联关系不能为空';
        }
        if(empty($value['table'])){
            return '关联数据表不能为空';
        }

        return true;
    }

    public function checkTableField($value)
    {
        if(preg_match('/[0-9]/',$value)){
            return '字段名不能添加数字';
        }
        $pattern = '/^(?!_)(?!.*_$)[a-z_]+$/';
        if(!preg_match($pattern,$value)){
            return '数据表字段请以小写字母和下划线格式添加,下划线不能在和结尾';
        }
        return true;
    }

    protected $scene = [
        'save' => [
            'module_id','form_title','table_field','type','order','status','is_null','attach_data','settings'
        ],
        'update' => [
            'id','form_title','table_field','type','order','status','is_null','attach_data','settings'
        ],
        'delete' => [
            'id','module'
        ],
    ];


}
